//
//  StandingsConvertTableViewController.m
//  EasyToTesco2.0
//
//  Created by knew on 16/9/12.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "StandingsConvertTableViewController.h"
#import "FirstCellTableViewCell.h"
#import "CaptchaView.h"
#import "RKAlertView.h"
#import "LastTableViewCell.h"
#import "StandTableViewCell.h"
#import "LoadUserName.h"
#import "UserNameTableViewCell.h"
#import "ChooseType.h"

@interface StandingsConvertTableViewController ()<UITextFieldDelegate,didSubmitButtonClickDelegate,SelectChooseTypeViewDelegate>

{
    NSString *_pwdString;
    UITextField *_userNameTextField;
    
    UIView *_alphaView;
    UIView *_showView;
}

@property (nonatomic,strong)NSArray *firstArray;

@property (nonatomic,strong)NSMutableArray *textFieldMutableArray;

@property (nonatomic,strong)NSArray *thiredCellArray;

@property (nonatomic,strong)UILabel *popularizeMoney;

@property (nonatomic,strong)NSArray *fourArray;

@property (nonatomic,strong)UITextField *verificationTextField;

@property (nonatomic,strong)CaptchaView *captcha;

@property(nonatomic,strong)UILabel *balanceLabel;

@property (nonatomic,strong)UIPickerView *pickerView;

@property (nonatomic,strong)NSMutableArray *pickerArray;

@property (nonatomic,strong)ChooseType *chooseType;
@end

@implementation StandingsConvertTableViewController


- (void)didSubmitButtonClick:(UIButton *)submitButton {
    UITextField *productName = self.textFieldMutableArray[0];
    
    UITextField *productMoney = self.textFieldMutableArray[1];
    
    UITextField *sellerNumber = self.textFieldMutableArray[2];
    
    UITextField *realName = self.textFieldMutableArray[3];
    
    if ((productName.text.length == 0)||(productMoney.text.length == 0)||(sellerNumber.text.length == 0)||(self.verificationTextField.text.length == 0) || (realName.text.length == 0)) {
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请确认信息输入无误" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
    } else {
        if (([productMoney.text floatValue] <=0)) {
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"金额和数量必须大于0" toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        } else if (![self.verificationTextField.text isEqualToString:self.captcha.changeString]) {
            
            [self textFieldAnimation:self.verificationTextField andSecondTextField:self.captcha.layer];
        } else {
            [RKAlertView showAlertPlainTextWithTitle:@"请输入二级密码" message:nil cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
                NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
                _pwdString = [alertView textFieldAtIndex:0].text;
                NSLog(@"%@",_pwdString);
                
                [self standingsConvert];
                
            } cancelBlock:^{
                //       NSLog(@"取消了");
            }];
        }
    }
    
}

- (void)standingsConvert {
    NSLog(@"%s",__FUNCTION__);
    
    UITextField *productName = self.textFieldMutableArray[0];
    
    UITextField *productMoney = self.textFieldMutableArray[1];
    
    UITextField *sellerNumber = self.textFieldMutableArray[2];
    
    UITextField *realName = self.textFieldMutableArray[3];
    
    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"zhenming":realName.text,
                             @"jine":productMoney.text,
                             @"title":productName.text,
                             @"bususername":sellerNumber.text,
                             @"safe_pass":_pwdString
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/User/hzcl" completeBlock:^(id object) {
        NSLog(@"%@",object);
        [JudgeBackDataCodeMessage JudgeBackDataCodeMessage:@"代金券兑换成功" andObjece:object andAddHUDView:self.view andPopViewController:^(id object) {
            
            for (UITextField *textField in self.textFieldMutableArray) {
                textField.text = @"";
            }
        }];
        
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"代金券兑换";
    
    self.tableView.bounces = NO;
    
    self.tableView.backgroundColor = BACKGROUND_COLOR;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
        
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
            
        case 1:
            return 1;
            break;
            
        case 2:
            return 2;
            break;
            
        case 3:
            return 3;
            break;
            
        default:
            return 0;
            break;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        FirstCellTableViewCell *first = [tableView dequeueReusableCellWithIdentifier:@"first"];
        if (first == nil) {
            first = [[FirstCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"first"];
            
            first.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        first.firstLabel.text = [self.firstArray[indexPath.row] objectForKey:@"label"];
        
        first.firstLabel.numberOfLines = 0;
        
        first.inPutTextField.placeholder = [self.firstArray[indexPath.row] objectForKey:@"placeholder"];
        
        first.inPutTextField.tag = indexPath.row;
        
        first.inPutTextField.userInteractionEnabled = NO;
        
        [self.textFieldMutableArray addObject:first.inPutTextField];
        
        if (indexPath.row == 0) {
            first.inPutTextField.delegate = self;
        } else {
            first.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
        }
        
        return first;
        
    } else if (indexPath.section == 2) {
        FirstCellTableViewCell *thired = [tableView dequeueReusableCellWithIdentifier:@"third"];
        
        if (!thired) {
            thired = [[FirstCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"third"];
            
            thired.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        thired.firstLabel.text = [self.thiredCellArray[indexPath.row]objectForKey:@"label"];
        thired.inPutTextField.placeholder = [self.thiredCellArray[indexPath.row] objectForKey:@"placeholder"];
        thired.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
        
        if (indexPath.row == 0) {
            thired.inPutTextField.tag = 1;
            thired.inPutTextField.delegate = self;
            thired.inPutTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            [self.textFieldMutableArray addObject:thired.inPutTextField];
            [thired.inPutTextField addTarget:self action:@selector(didPopularizeTextChangeMoney:) forControlEvents:UIControlEventEditingChanged];
        } else {
            thired.rightLabel.hidden = NO;
            thired.inPutTextField.hidden = YES;
            thired.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
            thired.rightLabel.text = @"0.00";
            thired.balanceLabel.hidden = false;
            
            if (self.voucherStr.length>0) {
                thired.balanceLabel.text = [NSString stringWithFormat:@"代金券:%@",self.voucherStr];
            }
            self.popularizeMoney = thired.rightLabel;
        }
        return thired;
    } else if (indexPath.section == 3 && indexPath.row == 0) {
        
        FirstCellTableViewCell *four = [tableView dequeueReusableCellWithIdentifier:@"four"];
        if (four == nil) {
            four = [[FirstCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"four"];
            
            four.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        four.firstLabel.text = @"商家号";
        
        four.inPutTextField.delegate = self;
        
        four.firstLabel.numberOfLines = 0;
        
        four.inPutTextField.placeholder = @"请输入商家号";
        
        four.inPutTextField.keyboardType = UIKeyboardTypeNumberPad;
        four.inPutTextField.tag = 2;
        [four.inPutTextField addTarget:self action:@selector(didClickSellerNumberChangeName:)forControlEvents:UIControlEventEditingChanged];
        [self.textFieldMutableArray addObject:four.inPutTextField];
        
        
        return four;
        
    } else if (indexPath.section == 3 && indexPath.row == 1) {
        UserNameTableViewCell *fourSecond = [tableView dequeueReusableCellWithIdentifier:@"four"];
        if (fourSecond == nil) {
            fourSecond = [[UserNameTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"four"];
            
            fourSecond.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        fourSecond.firstLabel.text = @"真实姓名";
        
        fourSecond.firstLabel.numberOfLines = 0;
        
        fourSecond.inPutTextField.placeholder = @"请输入姓名";
        
        _userNameTextField = fourSecond.inPutTextField;
        
        fourSecond.inPutTextField.tag = 3;
        
        [self.textFieldMutableArray addObject:fourSecond.inPutTextField];
        
        return fourSecond;
        
    } else if (indexPath.section == 3 && indexPath.row == 2) {
        
        LastTableViewCell *lastCell = [tableView dequeueReusableCellWithIdentifier:@"last"];
        
        if (!lastCell) {
            lastCell = [[LastTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"last"];
            
            lastCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        lastCell.noticeLabel.text = @"注: 产品金额单笔最大为50000";
        
        lastCell.delegate = self;
        lastCell.verificationTextField.tag = 4;
        lastCell.verificationTextField.delegate = self;
        self.verificationTextField = lastCell.verificationTextField;
        self.captcha = lastCell.Captcha;
        [self.textFieldMutableArray addObject:lastCell.verificationTextField];
        
        return lastCell;
        
    } else {
        StandTableViewCell *second = [tableView dequeueReusableCellWithIdentifier:@"four"];
        if (second == nil) {
            second = [[StandTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"four"];
            
            second.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        second.firstLabel.text = @"会员支付方式";
        
        return second;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0.001;
    }
    
    return 10;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 3 && indexPath.row == 2) {
        return HEIGHT - 5 * 44 - 164;
    }else if(indexPath.section == 0) {
        return 70;
    }else{
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self clearAllTextFieldResignFirstResponder];
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{} AndMenthodName:@"api/Hz/types" completeBlock:^(id object) {
            NSArray *array = [object[@"data"] objectForKey:@"types"];
            self.chooseType = [[ChooseType alloc] initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT)WithDataArray:array];
            self.chooseType.delegate = self;
            [self.view addSubview:self.chooseType];
            [self.chooseType showPickerView];

        }];
        
    }
    
}

- (void)SelectChooseTypeViewCityStr:(NSString *)typeName {
    UITextField *textField = self.textFieldMutableArray[0];
    textField.text = typeName;
}

- (void)SelectChooseTypeViewCancle {
    [self.chooseType dismissPickerView];
}

- (void)textFieldAnimation:(UITextField *)inPutTextField andSecondTextField:(CALayer *)SecondTextField {
    if (![inPutTextField.text isEqualToString:self.captcha.changeString]) {
        NSLog(@"%@",self.captcha.changeString);
        //验证不匹配，验证码和输入框晃动
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        anim.repeatCount = 1;
        anim.values = @[@-10, @10, @-10];
        [SecondTextField addAnimation:anim forKey:nil];
        [inPutTextField.layer addAnimation:anim forKey:nil];
    }
    
}

- (void)didPopularizeTextChangeMoney:(UITextField *)textField {
    
    UITextField *popularizeTextField = self.textFieldMutableArray[1];
    
    if (textField == popularizeTextField) {
        //        NSLog(@"%@",textField.text);
        
        self.popularizeMoney.text = [NSString stringWithFormat:@"%.2f",textField.text.floatValue * 0.08];
        if (textField.text.integerValue >= 50000) {
            self.popularizeMoney.text = [NSString stringWithFormat:@"%.2f",50000 * 0.08];
            textField.text = @"50000";
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UITextField *popularizeTextField = self.textFieldMutableArray[1];
    
    if (textField == popularizeTextField) {
        BOOL isHaveDian = YES;
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            isHaveDian=NO;
        }
        if (string.length) {
            unichar single=[string characterAtIndex:0];//当前输入的字符
            
            if ((single >='0' && single<='9') || single=='.')//数据格式正确
            {
                //首字母不能为小数点
                if([textField.text length]==0){
                    if(single == '.'){
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                        
                    }
                }
            } else {
                return NO;
            }
            
            if (single=='.') {
                if(!isHaveDian){
                    //text中还没有小数点
                    
                    isHaveDian=YES;
                    return YES;
                } else {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            } else {
                if (isHaveDian) {
                    //存在小数点
                    //判断小数点的位数
                    NSRange ran=[textField.text rangeOfString:@"."];
                    NSInteger tt=range.location-ran.location;
                    if (tt <= 1){
                        return YES;
                    }else{
                        return NO;
                    }
                } else {
                    return YES;
                }
            }
        }
    }
    
    return YES;
}

- (void)didClickSellerNumberChangeName:(UITextField *)textField {
    
    
    UITextField *sellerNumber = self.textFieldMutableArray[2];
    
    if (textField == sellerNumber) {
        if (textField.text.length >=11) {
            textField.text = [textField.text substringToIndex:11];
        }
        if (textField.text.length >10) {
            [LoadUserName loadUserNameWithPhoneNumber:sellerNumber.text andCompleteUserName:^(NSString *userName) {
                _userNameTextField.text = userName;
            } and:self.view];
        } else {
            _userNameTextField.text = @"";
        }
    }
    
}

- (void)clearAllTextFieldResignFirstResponder {
    
    for (UITextField *textField in self.textFieldMutableArray) {
        
        [textField resignFirstResponder];
        
        if (textField == self.textFieldMutableArray[1]) {
            self.popularizeMoney.text = [NSString stringWithFormat:@"%.2f",textField.text.floatValue * 0.08];
            if (textField.text.integerValue >= 50000) {
                self.popularizeMoney.text = [NSString stringWithFormat:@"%.2f",50000 * 0.08];
                textField.text = @"50000";
            }
        }
    }
}

- (NSArray *)firstArray {
    if (!_firstArray) {
        _firstArray = @[
                        @{
                            @"label":@"购买产品\n及数量",
                            @"placeholder":@"请输入产品名称及数量"
                            }
                        ];
    }
    return _firstArray;
}

- (NSArray *)thiredCellArray {
    if (!_thiredCellArray) {
        _thiredCellArray = @[
                             @{
                                 @"label":@"产品金额",
                                 @"placeholder":@"请输入产品金额"
                                 },
                             
                             @{
                                 @"label":@"产品推广费",
                                 @"placeholder":@""
                                 }
                             ];
    }
    return _thiredCellArray;
}

- (NSArray *)fourArray {
    if (!_fourArray) {
        _fourArray = @[
                       @{
                           @"label":@"商家号",
                           @"placeholder":@"请输入商家号"
                           },
                       
                       @{
                           @"label":@"真是姓名",
                           @"placeholder":@"请输入姓名"
                           }
                       ];
    }
    return _fourArray;
}

- (NSMutableArray *)textFieldMutableArray {
    if (!_textFieldMutableArray) {
        _textFieldMutableArray = [NSMutableArray array];
    }
    return _textFieldMutableArray;
}

- (NSMutableArray *)pickerArray {
    if (!_pickerArray) {
        _pickerArray = [NSMutableArray array];
    }
    return _pickerArray;
}

@end
